<template>
  <div class="account-container">
    <a-card title="账户管理">
      <template #extra>
        <a-space>
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索账户"
            style="width: 200px"
            @search="handleSearch"
          />
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增账户
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'active' ? 'green' : 'red'">
              {{ record.status === 'active' ? '活跃' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" danger @click="handleDelete(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑对话框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formData.username" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formData.email" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formData.phone" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formData.status">
            <a-select-option value="active">活跃</a-select-option>
            <a-select-option value="disabled">禁用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { accountService } from '@/services/accountService'

// 搜索文本
const searchText = ref('')

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '账户编号',
    dataIndex: 'accountNo',
    key: 'accountNo'
  },
  {
    title: '账户名称',
    dataIndex: 'accountName',
    key: 'accountName'
  },
  {
    title: '账户类型',
    dataIndex: 'accountTypeName',
    key: 'accountTypeName'
  },
  {
    title: '余额',
    dataIndex: 'balance',
    key: 'balance'
  },
  {
    title: '可用余额',
    dataIndex: 'availableBalance',
    key: 'availableBalance'
  },
  {
    title: '状态',
    dataIndex: 'statusName',
    key: 'statusName'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
]

// 表格数据
const dataSource = ref([])

// 加载状态
const loading = ref(false)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const modalVisible = ref(false)
const modalTitle = ref('新增账户')
const formData = reactive({
  id: null,
  accountNo: '',
  accountName: '',
  accountType: 1,
  balance: 0,
  frozenAmount: 0,
  status: 1,
  currency: 'CNY',
  openDate: new Date().toISOString().split('T')[0]
})

// 加载账户列表
const loadAccounts = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchText.value || undefined
    }
    const response = await accountService.getList(params)
    dataSource.value = response.list || []
    pagination.total = response.total || 0
  } catch (error) {
    message.error('加载账户列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadAccounts()
})

// 搜索
const handleSearch = (value) => {
  pagination.current = 1
  loadAccounts()
}

// 新增
const handleAdd = () => {
  modalTitle.value = '新增账户'
  Object.assign(formData, {
    id: null,
    accountNo: '',
    accountName: '',
    accountType: 1,
    balance: 0,
    frozenAmount: 0,
    status: 1,
    currency: 'CNY',
    openDate: new Date().toISOString().split('T')[0]
  })
  modalVisible.value = true
}

// 编辑
const handleEdit = (record) => {
  modalTitle.value = '编辑账户'
  Object.assign(formData, record)
  modalVisible.value = true
}

// 删除
const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除账户 ${record.accountName} 吗?`,
    async onOk() {
      try {
        await accountService.delete(record.id)
        message.success('删除成功')
        loadAccounts()
      } catch (error) {
        message.error('删除失败: ' + error.message)
      }
    }
  })
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadAccounts()
}

// 对话框确认
const handleModalOk = async () => {
  try {
    if (formData.id) {
      await accountService.update(formData)
      message.success('更新成功')
    } else {
      await accountService.create(formData)
      message.success('创建成功')
    }
    modalVisible.value = false
    loadAccounts()
  } catch (error) {
    message.error('保存失败: ' + error.message)
  }
}

// 对话框取消
const handleModalCancel = () => {
  modalVisible.value = false
}
</script>

<style scoped>
.account-container {
  max-width: 1400px;
}
</style>